﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;

namespace GetTogether.Studio.Logging
{
    public class Util
    {
        public static string GetPage(string url)
        {
            HttpWebRequest r = (HttpWebRequest)WebRequest.Create(url);
            r.SendChunked = false;
            r.Method = "GET";
            r.KeepAlive = true;
            r.Referer = url;
            r.Accept = "text/html, application/xml;q=0.9, application/xhtml xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1";
            r.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0";
            r.ContentType = "text/html; charset=UTF-8";
            string result = GetTogether.Utility.RequestHelper.GetResponse(r.GetResponse());
            return result;
        }

        public static Loggings GetLoggings(string url)
        {
            string page = Util.GetPage(url);
            if (string.IsNullOrEmpty(page)) return null;
            page = page.Replace("<br>", "\r\n").Replace("<tr>", "\t\n<tr>");
            Regex regx = new Regex(@"(?<MMMM_ddComma_yyyy>[A-Z|a-z]{1,}[ ]{1,}[0-9|,]{1,}[ ]{1,}[0-9]{4})?(?<Date>[0-9]{1,4}/[0-9]{1,2}/[0-9]{1,4})?[ ]{1,50}(?<Time>[0-9]{1,2}:[0-9]{1,2})[ ]{1,50}(?<TimeFlag>AM|PM)?[ ]{1,50}(?<Size>[0-9]{1,1000}|.*)<[a|A]{1} [HREF|href]{4}=""(?<Href>.*)"">(?<Name>.*)<\/[a|A]{1}>", RegexOptions.None);
            MatchCollection matchs = regx.Matches(page);
            if (matchs.Count == 0) matchs = new Regex(@"(<[a|A]{1} [HREF|href]{4}=""(?<Href>.*)"">(?<Name>.*)<\/[a|A]{1}>.*(?<Date>[0-9]{2}-[0-9|a-z|A-Z]{1,3}-[0-9]{1,4})[ ]{1,50}(?<Time>[0-9]{1,2}:[0-9]{1,2})[ ]{1,50}.*((>|[ ])((?<Size>[0-9|.]{1,99999}[a-z|A-Z]{1})|-)))").Matches(page);
            Loggings result = new Loggings();
            foreach (Match m in matchs)
            {
                if (m.Success)
                {
                    Loggings.Logging log = new Loggings.Logging();
                    log.Name = m.Groups["Name"].Value;
                    if (log.Name == "Parent Directory" || log.Name == "[To Parent Directory]")
                    {
                        continue;
                    }
                    log.Href = m.Groups["Href"].Value;
                    string date = m.Groups["Date"].Value;
                    string MMMM_ddComma_yyyy = m.Groups["MMMM_ddComma_yyyy"].Value;
                    string size = m.Groups["Size"].Value;
                    if (!string.IsNullOrEmpty(size))
                    {
                        size = size.Trim().ToUpper();
                        if (size.IndexOf("DIR") < 0)
                        {
                            log.Size = GetTogether.Utility.StringHelper.GetSizeString(size);
                        }
                    }
                    log.DateString = date;
                    if (string.IsNullOrEmpty(log.DateString)) log.DateString = MMMM_ddComma_yyyy;
                    if (!string.IsNullOrEmpty(date))
                        log.Date = DateTime.Parse(date);
                    else
                        log.Date = DateTime.ParseExact(MMMM_ddComma_yyyy, "MMMM dd, yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                    string time = m.Groups["Time"].Value;
                    string timeFlag = m.Groups["TimeFlag"].Value;
                    if (!string.IsNullOrEmpty(time))
                    {
                        log.DateString = string.Concat(log.DateString, " ", time, " ", timeFlag);
                        TimeSpan timeOfDay = new TimeSpan();
                        TimeSpan.TryParse(time, out timeOfDay);
                        log.Date = log.Date.AddHours(timeOfDay.Hours);
                        log.Date = log.Date.AddMinutes(timeOfDay.Minutes);
                        if (!string.IsNullOrEmpty(timeFlag) && timeFlag.Trim().ToUpper() == "PM")
                        {
                            log.Date = log.Date.AddHours(12);
                        }
                    }
                    if (!string.IsNullOrEmpty(log.Href)
                        && !string.IsNullOrEmpty(log.Name)
                        && log.Href.Trim() != "/"
                        && !log.Href.EndsWith(".bz2")
                        && !log.Href.EndsWith(".rar"))
                    {
                        log.IsFile = !log.Href.EndsWith("/");
                        if (log.IsFile)
                        {
                            string file = log.Href.Trim().ToLower();
                            if (file.EndsWith(".cs") || file.EndsWith(".aspx"))
                                log.IsCodeFile = true;
                        }
                        result.Add(log);
                    }
                }
            }
            return result;
        }
    }
}